<?php
/**
 * 广播
 * @author jiangyong<jiangyong.go@qq.com>
 * @date   2025/6/5
 */

namespace App\Http\Controllers;

use App\Events\AllBroadcastEvent;
use App\Events\DefaultBroadcastEvent;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Spatie\RouteAttributes\Attributes\Any;
use Spatie\RouteAttributes\Attributes\Middleware;
use Spatie\RouteAttributes\Attributes\Prefix;
use Illuminate\Http\Request;

#[Prefix('broadcast')]
class BroadcastController extends Controller
{
    public $user;
    public function __construct()
    {
        //$this->middleware(['web','auth']);
        $this->middleware(function ($request, $next) {
            //$request->user = Auth::user();
            $request->user = User::find(1);
            return $next($request);
        });
    }

    #[Any('send')]
    public function send(request $request)
    {
        $user =   $request->user;
        broadcast(new DefaultBroadcastEvent($user));
        //broadcast(new AllBroadcastEvent('广播'));
        //event(new DefaultBroadcastEvent($user));

    }

    #[Any('/')]
    public function index(request $request)
    {
        $user =   $request->user;
        return $user ?? 'no user';
    }

    /**
     * 广播的前端监听视图文件
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    #[Any('echo', middleware: ['web','auth'])]
    public function echo(request $request)
    {
        return view('broadcast');
    }

    /**
     * 前端监听私有频道 认证
     * @param Request $request
     * @author jiangyong<jiangyong.go@qq.com>
     * @date   2025/6/16 12:22
     */
    #[Any('user', middleware: ['web','auth'])]
    public function user(request $request)
    {
        $user = Auth::user();
        return $user ?? 'no user';
    }

    #[Any('checkenv')]
    public function checkenv(request $request)
    {
        Redis::set('abc', 1);
        return Redis::get('abc');
    }

}
